package com.glsc.ngateway.platform.service.itflow.flowstrategy.equipmentServerApply.taskPostHandler;

import com.glsc.ngateway.common.api.common.enums.RabbitExcQueConstant;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItServerDevice;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.flow.FlowFormEquipmentServerApply;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.flow.FlowFormEquipmentServerApplyServerDetail;
import com.glsc.ngateway.common.api.flowable.dto.task.doTaskParam.equipment.EquipmentPassParamDto;
import com.glsc.ngateway.common.api.flowable.dto.task.doTaskParam.equipment.EquipmentRejectParamDto;
import com.glsc.ngateway.common.api.flowable.dto.task.formData.equipment.EquipmentServerApplyTaskFormDataDto;
import com.glsc.ngateway.common.api.flowable.dto.task.formData.equipment.domainDto.FlowFormEquipmentServerApplyDto;
import com.glsc.ngateway.common.api.flowable.dto.task.message.EquipmentFlowMessageDto;
import com.glsc.ngateway.common.api.flowable.resp.ResponseSituationDto;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.FlowFormEquipmentServerApplyRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.FlowFormEquipmentServerApplyServerRepo;
import com.glsc.ngateway.platform.service.FlowCommonService;
import com.glsc.ngateway.platform.service.it.ServerService;
import com.glsc.ngateway.platform.service.itflow.flowstrategy.AbstractHandlerHelper;
import com.glsc.ngateway.common.api.common.utils.DateUtil;
import com.glsc.ngateway.platform.utils.MqUtil;
import com.glsc.ngateway.common.base.enums.itflow.ITFlowStatus;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

/**
 * 设备变更节点辅助类
 *
 * @author xuchang
 */
@Component
public class ESAStepHandlerHelper extends AbstractHandlerHelper {

    @Autowired
    private FlowFormEquipmentServerApplyRepo equipmentServerApplyRepo;

    @Autowired
    private FlowCommonService flowCommonService;

    @Autowired
    private ServerService serverService;

    @Autowired
    private FlowFormEquipmentServerApplyServerRepo equipmentServerApplyServerRepo;

    /**
     * 最后审批后置处理
     */
    protected void endTaskAfterHandle(EquipmentPassParamDto<FlowFormEquipmentServerApplyDto, EquipmentServerApplyTaskFormDataDto> param, String operator, String mqCodeKey) {
        ResponseSituationDto processInfo = flowCommonService.getProcessInfo(param.getProcessId());
        if (Collections.isEmpty(processInfo.getCurrentTaskInfoDtoList())) {
            EquipmentFlowMessageDto message = new EquipmentFlowMessageDto();
            FlowFormEquipmentServerApply serverApply = equipmentServerApplyRepo.findByProcessId(param.getProcessId());
            message.setMainFormId(serverApply.getId());
            message.setDefineKey(mqCodeKey);
            message.setOperator(operator);
            MqUtil.sendMessage(RabbitExcQueConstant.AMPRODUCT_EXCHANGE_DEFAULT, RabbitExcQueConstant.AMPRODUCT_QUEUE_GATEWAY_FLOW_REMIND, message);
        }
    }

    /**
     * 驳回后置处理方法
     */
    protected void afterHandle(@NotNull EquipmentRejectParamDto param, @NotNull String operator) {
        List<FlowFormEquipmentServerApply> formDataList = equipmentServerApplyRepo.findAllByProcessId(param.getProcessId());
        formDataList.forEach(f->{
            f.setUpdateAccount(operator);
        });
        equipmentServerApplyRepo.saveAll(formDataList);
    }

    /**
     * 将剩余信息更新
     */
    protected void fillOtherData(EquipmentServerApplyTaskFormDataDto data) {
        data.getFormServerDataList().forEach(server -> {
            FlowFormEquipmentServerApplyServerDetail serverApply = equipmentServerApplyServerRepo.findById(server.getId())
                    .orElseThrow(() -> PlatformException.error(String.format("物理设备申领及上架，异常：未找到主表数据，%s", server.getId())));
            serverApply.setMachineUnit(server.getMachineUnit());
            serverApply.setCapitalType(server.getCapitalType());
            serverApply.setBrand(server.getBrand());
            serverApply.setBrandType(server.getBrandType());
            serverApply.setCcTime(server.getCcTime());
            serverApply.setSjTime(server.getSjTime());
            serverApply.setMachineRoom(server.getMachineRoom());
            serverApply.setMachineCab(server.getMachineCab());
            serverApply.setCapitalStyle(server.getCapitalStyle());
            serverApply.setPnPid(server.getPnPid());
            serverApply.setSn(server.getSn());
            serverApply.setPlanOn(server.getPlanOn());
            serverApply.setMac1(server.getMac1());
            serverApply.setMac2(server.getMac2());
            serverApply.setMac3(server.getMac3());
            serverApply.setMac4(server.getMac4());
            serverApply.setQj(server.getQj());
            serverApply.setCapitalTyped(server.getCapitalTyped());
            serverApply.setSupportPower(server.getSupportPower());
            serverApply.setNetworkSegment(server.getNetworkSegment());
            serverApply.setIlo(server.getIlo());
            equipmentServerApplyServerRepo.save(serverApply);
        });
    }

    public void applyServerEquipment(Long mainFormId) {
        FlowFormEquipmentServerApply serverApply = equipmentServerApplyRepo.findById(mainFormId)
                .orElseThrow(() -> PlatformException.error(String.format("物理设备申领及上架，消息处理异常：未找到主表数据，%s", mainFormId)));
        //幂等
        if (serverApply.getIsClose() == 0) {
            //审核通过后需要新增设备的信息
            //增加物理设备
            applyServerDevice(mainFormId);
            serverApply.setStatus(ITFlowStatus.END.getCode());
            serverApply.setIsClose(1);
            equipmentServerApplyRepo.save(serverApply);
        }
    }

    private void applyServerDevice(Long mainFormId) {
        List<FlowFormEquipmentServerApplyServerDetail> applyServerList = equipmentServerApplyServerRepo.findByEquipmentServerApplyId(mainFormId);
        applyServerList.forEach(server -> {
            ItServerDevice convert = new ItServerDevice();
            convert.setBusinessName(server.getBusinessName());
            convert.setApplicationDetail(server.getApplicationDetail());
            convert.setMachineRoom(server.getMachineRoom());
            convert.setMachineCab(server.getMachineCab());
            convert.setMachineUnit(server.getMachineUnit());
            convert.setCapitalTyped(server.getCapitalTyped());
            convert.setCapitalType(server.getCapitalType());
            convert.setCapitalStyle(server.getCapitalStyle());
            convert.setBrand(server.getBrand());
            convert.setBrandType(server.getBrandType());
            convert.setPnPid(server.getPnPid());
            convert.setSn(server.getSn());
            convert.setOperationSys(server.getOperationSys());
            convert.setDiskType(server.getDiskType());
            convert.setCpu(server.getCpu());
            convert.setMemory(server.getMemory());
            convert.setUserId(server.getUserId());
            convert.setCcTime(server.getCcTime().atStartOfDay());
            convert.setWbTime(server.getWbTime().atStartOfDay());
            convert.setSjTime(server.getSjTime().atStartOfDay());
            if (Objects.nonNull(server.getCcTime())) {
                convert.setCcTimeStr(DateUtil.getStr_yyyyMMdd2(convert.getCcTime()));
            }
            if (Objects.nonNull(server.getWbTime())) {
                convert.setCcTimeStr(DateUtil.getStr_yyyyMMdd2(convert.getWbTime()));
            }
            if (Objects.nonNull(server.getSjTime())) {
                convert.setCcTimeStr(DateUtil.getStr_yyyyMMdd2(convert.getSjTime()));
            }
            convert.setPlanOn(server.getPlanOn());
            convert.setSupportPower(server.getSupportPower());
            convert.setBz(server.getBz());
            convert.setMachineStatus(server.getMachineStatus());
            convert.setMac1(server.getMac1());
            convert.setMac2(server.getMac2());
            convert.setMac3(server.getMac3());
            convert.setMac4(server.getMac4());
            convert.setMac5(server.getMac5());
            convert.setMac6(server.getMac6());
            convert.setMac7(server.getMac7());
            convert.setMac8(server.getMac8());
            convert.setMac9(server.getMac9());
            convert.setMac10(server.getMac10());
            convert.setMac11(server.getMac11());
            convert.setMac12(server.getMac12());
            convert.setIp1(server.getIp1());
            convert.setIp2(server.getIp2());
            convert.setIp3(server.getIp3());
            convert.setIp4(server.getIp4());
            convert.setQj(server.getQj());
            convert.setFixRecord(server.getFixRecord());
            convert.setFixTime(server.getFixTime().atStartOfDay());
            convert.setFixTimeStr(DateUtil.getStr_yyyyMMdd2(convert.getFixTime()));
            convert.setBf(server.getBf());
            convert.setNetworkSegment(server.getNetworkSegment());
            convert.setIlo(server.getIlo());
            serverService.addOrUpdateServer(convert);
        });
    }
}
